package com.sanji.sjmallmodule.order;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sanji.sjmallapp.BaseActivity;
import com.sanji.sjmallapp.R;
import com.sanji.sjmallconfig.ConfigAPI;
import com.sanji.sjmallconfig.ConfigConts;
import com.sanji.sjmallmanager.http.NoHttpCallBack;
import com.sanji.sjmallmanager.http.NoHttpListener;
import com.sanji.sjmallutils.SharePreferenceUtil;
import com.sanji.sjmallutils.Tools;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.RequestMethod;
import com.yolanda.nohttp.rest.Request;
import com.yolanda.nohttp.rest.Response;

import org.json.JSONArray;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 支付页面
 **/
public class OrderPayActivity extends BaseActivity implements View.OnClickListener, NoHttpListener {

    private static final int REQUEST_ALIPAY = 50000;

    @BindView(R.id.common_title_tv)
    TextView commonTitleTv;
    @BindView(R.id.common_back_img)
    ImageView commonBackImg;
    @BindView(R.id.pop_paymeng_onling)
    RelativeLayout onlineLayout;
    @BindView(R.id.pop_paymeng_alipay_cb)
    CheckBox paymengAlipayCb;
    @BindView(R.id.pop_paymeng_offline)
    RelativeLayout offlineLayout;
    @BindView(R.id.pop_paymeng_offline_cb)
    CheckBox paymengOfflineCb;
    @BindView(R.id.pop_payment_submit)
    Button paymentSubmit;
    @BindView(R.id.pop_payment_coast)
    TextView paymentCoast;
    private String orderId;
    private Double actualAmount;//实付金额
    private String payType = "SJ-ZFB";
    private SharePreferenceUtil sp;
    private String[] payTypes;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_pay);
        ButterKnife.bind(this);
        initView();
    }

    public void initView() {
        sp = myShare;
        commonTitleTv.setText(getString(R.string.title_order_pay));
        commonBackImg.setOnClickListener(this);
        paymentSubmit.setOnClickListener(this);

        orderId = getIntent().getStringExtra("orderId");
        actualAmount = getIntent().getDoubleExtra("actualAmount", 0);
        payTypes = getIntent().getStringArrayExtra("payType");
        paymentCoast.setText(getString(R.string.price_title) + actualAmount);

        if (payTypes!=null && payTypes.length>0){
            for(int i=0;i<payTypes.length;i++){
                if ("SJ-ZFB".equals(payTypes[i])){
                    onlineLayout.setVisibility(View.VISIBLE);
                }else if("SJ-HDFK".equals(payTypes[i])){
                    offlineLayout.setVisibility(View.VISIBLE);
                }
            }
        }else{
            payType = "";
        }


//        findViewById(R.id.pop_paymeng_onling).setOnClickListener(this);

        paymengAlipayCb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    payType = "SJ-ZFB";
                    paymengOfflineCb.setChecked(false);
                } else {
                    payType = "SJ-HDFK";
                    paymengOfflineCb.setChecked(true);
                }
            }
        });

        paymengOfflineCb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    payType = "SJ-HDFK";
                    paymengAlipayCb.setChecked(false);
                } else {
                    payType = "SJ-ZFB";
                    paymengAlipayCb.setChecked(true);
                }

            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_back_img:
                finish();
                break;
            case R.id.pop_paymeng_onling:
//                //选择支付方式
//                intent = new Intent(this, AliPayWebViewActivity.class);
//                intent.putExtra("aliUrl", "https://ds.alipay.com/?from=mobilecodec&scheme=alipays%3A%2F%2Fplatformapi%2Fstartapp%3FsaId%3D10000007%26clientVersion%3D3.7.0.0718%26qrcode%3Dhttps%253A%252F%252Fqr.alipay.com%252Fbax07799fctvumfzj9av4008%253F_s%253Dweb-other");
//                startActivityForResult(intent, REQUEST_ALIPAY);

                break;
            case R.id.pop_payment_submit:
                //确认付款
//                myShare.put(ConfigConts.IsRefresh, true);


                if ("".equals(payType)) {
                    Tools.toastTools(mCtx, getString(R.string.select_pay_method));
                    return;
                }

                try {
                    JSONObject json = new JSONObject();
                    json.put("userId", myShare.getString(ConfigConts.USER_ID, ""));
                    json.put("orderId", orderId);
                    json.put("frpId", payType);
                    json.put("payPwd", "");


                    Request<JSONObject> payRequest = NoHttp.createJsonObjectRequest(ConfigAPI.ORDER_PAY_URL, RequestMethod.POST);
                    payRequest.setDefineRequestBodyForJson(json);
                    NoHttpCallBack.getInstance().add(this, ConfigAPI.ORDER_PAY_URL.hashCode(), payRequest, this, true, true);

                } catch (Exception e) {
                    e.printStackTrace();

                }
                break;
        }

    }

    @Override
    public void onSuccessed(int what, Response response) {
        try {
            JSONObject respJson = new JSONObject(response.get().toString());
            String status = respJson.optString("status");
            if (ConfigConts.STATUS_SUCCESS.equals(status)) {

                if (what == ConfigAPI.ORDER_QUERY.hashCode()) {
                    //订单查询
                    setResult(RESULT_OK, null);
                    finishActivity();
                } else if (what == ConfigAPI.ORDER_PAY_URL.hashCode()) {
                    if ("SJ-ZFB".equals(payType)) {
                        String aliUrl = respJson.optString("successMsg");
                        intent = new Intent(this, AliPayWebViewActivity.class);
                        intent.putExtra("aliUrl", aliUrl);
                        startActivityForResult(intent, REQUEST_ALIPAY);
                    } else {
                        Tools.toastTools(mCtx, getString(R.string.pay_status_success));
                        intent = new Intent(this, PaySuccessMessageActivity.class);
                        startActivity(intent);
                        setResult(RESULT_OK, null);
                        finishActivity();
                    }
                }
            } else {
                String error = respJson.optString("errorMsg");
                Tools.toastTools(mCtx, error);
                finishActivity();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onFailed(int what, Response response) {

        Tools.toastTools(mCtx, getString(R.string.request_false)+ response.get().toString());
    }

    private void orderQuery() {
        try {
            JSONObject json = new JSONObject();
            json.put("orderId", orderId);

            Request<JSONObject> payRequest = NoHttp.createJsonObjectRequest(ConfigAPI.ORDER_QUERY, RequestMethod.POST);
            payRequest.setDefineRequestBodyForJson(json);
            NoHttpCallBack.getInstance().add(mCtx, ConfigAPI.ORDER_QUERY.hashCode(), payRequest, this, true, true);

        } catch (Exception e) {
            e.printStackTrace();

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_ALIPAY && resultCode == RESULT_OK) {
            //启动支付

            AlertDialog.Builder dialog = new AlertDialog.Builder(mCtx);
            dialog.setTitle("支付返回");
            dialog.setMessage("支付完成后，请根据您的支付情况点击下面的按钮");
            dialog.setPositiveButton("支付完成", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    orderQuery();
                    dialog.dismiss();

                }
            });
            dialog.setNegativeButton("支付遇到问题", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            dialog.create();
            dialog.show();

        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
